/************************************************************************
  * Copyright(c) 2023 Levetop Semiconductor Co.,Led. All rights reserved.
  * @file     tp_iic.c
  * @author   UartTFT Application Team
  * @version  V0.0.1
  * @date     2023-01-01
  * @brief     
 *************************************************************************/

#include "tp_iic.h"
#include "delay.h"
#include "tp_ctp.h"

/* simulation I2C */

/*****************************CTI2C_delay***************************/
void CTI2C_delay(uint32_t val)
{
	for (int32_t i = 0; i < val * 60; i++) // val*30  350kHZ
	{
		//__NOP;
		__asm("nop");
	}
}

/*****************************CTI2C_Start***************************/
uint8_t CTI2C_Start(void)
{
	CTP_SCL_HIGH;
	CTP_SDA_HIGH;
	CTI2C_delay(1);
//		CTP_SDA_INPUT;
//		CTI2C_delay(1);
//		if(!CTP_GetSDABit)
//		{
//			CTP_SDA_OUTPUT;
//			printf("CTI2C_Start  BUSY \r\n"); //bus busy
//			return  1;
//		}
//		CTP_SDA_OUTPUT;
	CTP_SDA_LOW;
	CTI2C_delay(1);
//		CTP_SDA_INPUT;
//		if(CTP_GetSDABit)
//		{
//			CTP_SDA_OUTPUT;
//			printf("CTI2C_Start  error \r\n"); //bus error
//			return  1;
//		}
//		CTP_SDA_OUTPUT;
	CTP_SCL_LOW;
	CTI2C_delay(1);

	return 0;
}

/*****************************CTI2C_Stop**************************/
uint8_t CTI2C_Stop(void)
{
	// CTP_SCL_LOW;
	CTP_SDA_LOW;
	CTI2C_delay(1);
	CTP_SCL_HIGH;
	CTI2C_delay(1);
	CTP_SDA_HIGH;
	CTI2C_delay(2);

	return 0;
}

/********************CTI2C_write_byte*****************/
uint8_t CTI2C_write_byte(const uint8_t s)
{
	uint8_t ch_data, i = 0;

	// CTP_SCL_LOW;
	ch_data = s;
	for (i = 0; i < 8; i++)
	{
		if (ch_data & 0x80)
			CTP_SDA_HIGH;
		else
			CTP_SDA_LOW;
		CTI2C_delay(1);
		CTP_SCL_HIGH;
		CTI2C_delay(1);
		CTP_SCL_LOW;
		CTI2C_delay(1);
		ch_data <<= 1;
	}
	// ACK
	CTP_SDA_INPUT;
	CTP_SDA_HIGH;
	CTI2C_delay(1);
	CTP_SCL_HIGH;
	CTI2C_delay(1);
	for (uint8_t i = 0; i < 200; i++)
	{
		if (!CTP_GetSDABit)
		{
			CTP_SCL_LOW;
			CTP_SDA_OUTPUT;
			CTI2C_delay(1);
			// printf("ack 0k \r\n");
			return 0; // ACK
		}
	}
	CTP_SCL_LOW;
	CTP_SDA_OUTPUT;
	CTI2C_Stop(); // ERROR
	CTI2C_delay(1);
	// printf("ack error \r\n");
	return 1; // NACK
}

/****************CTI2C_read_byte*****************/
uint8_t CTI2C_read_byte(uint8_t ack)
{
	uint8_t ch_data = 0x00, i = 0;

	CTP_SDA_INPUT;
	CTP_SDA_HIGH;
	CTI2C_delay(1);
	for (i = 0; i < 8; i++)
	{
		CTP_SCL_LOW;
		CTI2C_delay(1);
		CTP_SCL_HIGH;
		CTI2C_delay(1);
		ch_data <<= 1;
		if (CTP_GetSDABit)
			ch_data |= 0x01;
	}
	// ACK

	CTP_SCL_LOW;
	CTI2C_delay(1);
	CTP_SDA_OUTPUT;
	if (ack)
		CTP_SDA_HIGH;
	else
		CTP_SDA_LOW;
	CTI2C_delay(1);
	CTP_SCL_HIGH;
	CTI2C_delay(1);
	CTP_SCL_LOW;
	CTI2C_delay(1);

	return ch_data;
}

